import { ref } from 'vue';
import store from '@/store';
import { defineStore } from 'pinia';
import { type RouteRecordRaw } from 'vue-router';
import { constantRoutes, dynamicRoutes } from '@/router';
import { flatMultiLevelRoutes } from '@/router/helper';
import routeSettings from '@/config/route';

// 用来放置有权限 (Roles 属性) 的路由
const hasPermission = (roles: string[], route: RouteRecordRaw) => {
	const routeRoles = route.meta?.roles;
	return routeRoles ? roles.some((role) => routeRoles.includes(role)) : true;
};

// 递归遍历 动态路由表匹配角色 过滤动态路由
const filterDynamicRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
	const res: RouteRecordRaw[] = [];
	routes.forEach((route) => {
		const tempRoute = { ...route };
		if (hasPermission(roles, tempRoute)) {
			if (tempRoute.children) {
				tempRoute.children = filterDynamicRoutes(tempRoute.children, roles);
			}
			res.push(tempRoute);
		}
	});
	return res;
};

export const usePermissionStore = defineStore('permission', () => {
	/** 可访问的路由 */
	const routes = ref<RouteRecordRaw[]>([]);
	/** 动态路由 有访问权限的 */
	const addRoutes = ref<RouteRecordRaw[]>([]);

	/** 根据角色生成可访问的 Routes（可访问的路由 = 常驻路由 + 有访问权限的动态路由） */
	const setRoutes = (roles: string[]) => {
		// 根据获取到的角色 去定义好的动态路由表中 匹配是否哪些路由可以访问
		const accessedRoutes = filterDynamicRoutes(dynamicRoutes, roles); // 过滤后的动态路由
		_set(accessedRoutes);
	};

	/** 所有路由 = 所有常驻路由 + 所有动态路由 */
	const setAllRoutes = () => {
		_set(dynamicRoutes);
	};

	const _set = (accessedRoutes: RouteRecordRaw[]) => {
		routes.value = constantRoutes.concat(accessedRoutes);
		addRoutes.value = routeSettings.thirdLevelRouteCache ? flatMultiLevelRoutes(accessedRoutes) : accessedRoutes; // 添加的的有权限访问的动态路由
	};

	return { routes, addRoutes, setRoutes, setAllRoutes };
});

/** 在 setup 外使用 */
export function usePermissionStoreHook() {
	return usePermissionStore(store);
}
